<?php

/**
 *This controller is responsible for processing search action
 *
 *@author Pavel Savchuk
 */
class Backend_SearchController extends RCMS_Core_BaseController {

/**
 * Variable for website Url
 *
 * @var string
 */
	protected $_websiteUrl;

	/**
	 * Variable for page Url
	 *
	 * @var string
	 */
	protected $_pageUrl;

	/**
	 * Variable for page Url
	 *
	 * @var string
	 */
	protected $_model;

	public function init() {
		$this->_websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		parent::init();
		$this->_model = new Default_Model_SearchModel();
		$this->_pageUrl =  ($this->getRequest()->getParam('requestedPage'))? str_replace(".html", "", $this->getRequest()->getParam('requestedPage')).".html" : "";
		//zend lucene
	
	}

	/**
	 * Process search
	 *
	 * @return void
	 */
	public function searchAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$data = null;
		$pageUrl = ($this->getRequest()->getParam('pageUrl'))? htmlspecialchars($this->getRequest()->getParam('pageUrl')) : '';
		if($this->getRequest()->isPost() && $this->getRequest()->getParam('searchtext') != '') {

			$searchtext = ($this->getRequest()->getParam('searchtext'))? htmlspecialchars($this->getRequest()->getParam('searchtext')) : '';

			$cacheKey = preg_replace('/[^a-zA-Z0-9_]/', '_', $searchtext) . '_search';
			if(!$data = $this->_cache->load($cacheKey)) {
				$this->createIndexSearchFile();
				if ($this->_checkPerlCompatible()) {
					Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
				}
				Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
				$index = Zend_Search_Lucene::open("tmp/lucene-index");
				$results = $index->find($searchtext);
				if($index->count()) {
					$count = 0;
					foreach ($results as $result) {
						$data[] = $result->page_id;
					}
					$this->_cache->save($data, $cacheKey);
				}
				
			}
			
			//assign data in session.
			if($data!=null && sizeof($data)>0) {
				$this->_session->searchResult = $data;
			}else {
				$this->_session->searchResult = "Nothing found";
			}
		}
		$this->_redirect($this->getWebSiteUrl().$pageUrl);
	}

	private function _checkPerlCompatible() {
		return (@preg_match('/\pL/u', 'a') == 1) ? true : false;
	}

	/**
	 * @method Creates Zend Lucene Search document
	 *
	 * @return void;
	 */
	public function createIndexSearchFile() {
	//if(!is_dir('tmp/lucene-index')) {
		$results = $this->_model->selectDataForSearchIndex();
		if(is_array($results) && count($results)) {
			if($this->_checkPerlCompatible()) {
				Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
			}
			Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
			$index = Zend_Search_Lucene::create('tmp/lucene-index');

			foreach($results as $result) {
				$doc = new Zend_Search_Lucene_Document();
				$doc->addField(Zend_Search_Lucene_Field::keyword('page_id',
					$result["id"]));

				$doc->addField(Zend_Search_Lucene_Field::Text('meta_keywords',
					$result["meta_keywords"]));

				$doc->addField(Zend_Search_Lucene_Field::Text('meta_description',
					$result["meta_description"]),"UTF-8");

				$doc->addField(Zend_Search_Lucene_Field::Text('short_description',
					$result["short_description"]),"UTF-8");

				$doc->addField(Zend_Search_Lucene_Field::Text('header_title',
					$result["header_title"]),"UTF-8");

				$doc->addField(Zend_Search_Lucene_Field::Text('value',
					trim($result["value"])),"UTF-8");
				$index->addDocument($doc);
			}
			$index->commit();
			$index->optimize();
		}
	//}
	}
}
